import path from 'path'
import fs from 'fs'
import fse from 'fs-extra'

export default () => {
  return {
    name: 'vite-load-assets',
    enforce: 'post',
    buildStart() {},
    writeBundle(bundle) {
      // 需要在打包结束后复制资源目录到输出目录
      const assetsPath = path.resolve('src/assets')
      fse.pathExists(assetsPath, (_err, exists) => {
        if (exists) {
          fse.copy(assetsPath, path.resolve('lib/assets'))
        }
      })

      // ace依赖文件复制到lib目录
      const acePath = path.resolve('plugins/ace/src-min-noconflict')
      fse.pathExists(acePath, (_err, exists) => {
        if (exists) {
          fse.copy(acePath, path.resolve('lib/ace/src-min-noconflict'))
        }
      })

      // 在生成的入口文件中添加导入样式文件的代码
      const styleFilePath = path.resolve(bundle.dir, 'style.css')
      fse.pathExists(styleFilePath, (_err, exists) => {
        if (exists) {
          const entryFilePath = path.resolve(bundle.dir, 'index.js')
          fs.appendFile(entryFilePath, "import './style.css';\n", () => {})
          fs.appendFile(entryFilePath, "import './assets/iconfont.js';\n", () => {})
          fs.appendFile(entryFilePath, "import './assets/iconfont.css';\n", () => {})
        }
      })
    }
  }
}
